﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EpiPoker.DataAccess;
using System.Xml.Serialization;
using System.Timers;
using System.ServiceModel;
using EpiPoker.NotifyService;

namespace EpiPoker
{
    public partial class Seat : System.Web.UI.UserControl
    {
        #region attributes
        private int number;
        private Boolean play = false;
        private Boolean isPlaying = false;
        private Boolean isDealer = false;
        private Boolean isSmallBlind = false;
        private Boolean isBigBlind = false;
        private T_User user = new T_User();
        private Objects.Hand hand;
        private int betPlayer;
        private Boolean next = false;
        #endregion

        #region getter/setter
        public int BetPlayer
        {
            get { return betPlayer; }
            set { betPlayer = value; }
        }

        public int Number
        {
            get { return number; }
            set { number = value; }
        }

        public Boolean Play
        {
            get { return play; }
            set { play = value; }
        }

        public Boolean IsPlaying
        {
            get { return isPlaying; }
            set { isPlaying = value; }
        }

        public Boolean IsDealer
        {
            get { return isDealer; }
            set { isDealer = value; }
        }

        public Boolean IsSmallBlind
        {
            get { return isSmallBlind; }
            set { isSmallBlind = value; }
        }

        public Boolean IsBigBlind
        {
            get { return isBigBlind; }
            set { isBigBlind = value; }
        }

        public T_User User
        {
            get { return user; }
            set { user = value; }
        }

        public Objects.Hand Hand
        {
            get { return hand; }
            set { hand = value; }
        }

        public String GetFirstName()
        {
            return SeatFirstName.Text;
        }

        public String AvatarURL()
        {
            return SeatAvatar.ImageUrl;
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            this.User = DataAccess.User.GetUserWithTableAndSeat(Table.Idtable, number);

            if (this.User != null)
            {
                JoinPlace.Visible = false;
                SeatAvatar.Visible = true;

                T_Portfolio portfolio = DataAccess.Portfolio.GetPortfolioByUserId(
                    long.Parse(Session["facebook_userId"].ToString()));
                int amount = (int)portfolio.Amount;

                SeatNbChips.Text = amount.ToString();
                SeatFirstName.Text = this.User.FirstName;
                SeatAvatar.ImageUrl = this.User.AvatarUrl;
            }
            else
                SeatAvatar.Visible = false;
        }

        protected void PlaceHere(object sender, EventArgs e)
        {
            AppFacebookService objFbService = (AppFacebookService)Session["fbService"];
            this.User = DataAccess.User.GetUser(long.Parse(Session["facebook_userId"].ToString()));

            // Update database field NumPlace
            this.User.NumPlace = (byte)Number;
            DataAccess.User.UpdateUser(this.User);

            // NOTE : What is List_seat for ?
            Table.List_seat[Number].User = this.User;
            Table.List_seat[Number].isPlaying = true;
            this.isPlaying = true;
            // Hide Sit Button on other seat than this one
            Table.HideSitButtons(this);

            Table.List_seat[this.Number] = this;

            NotifyServiceCallback notification = new NotifyServiceCallback();
            InstanceContext instanceContext = new InstanceContext(notification);
            NotifyService.NotifyServiceClient service = new NotifyServiceClient(instanceContext);
            service.GetData(Table.List_seat.ToArray(), (Table)this.Page);

            this.Update(sender, e);
        }

        public void Update(object sender, EventArgs e)
        {
            foreach (var item in Table.List_seat)
            {
                if (item.isPlaying == true)
                {
                    item.JoinPlace.Visible = false;
                    item.SeatAvatar.ImageUrl = Table.List_seat[item.number].SeatAvatar.ImageUrl;
                    item.SeatNbChips.Text = Table.List_seat[item.number].SeatNbChips.Text;
                    item.SeatFirstName.Text = Table.List_seat[item.number].SeatFirstName.Text;
                }
            }
        }

        public void HideSitButton()
        {
            this.SeatFirstName.Text = "LOUL";
            //this.JoinPlace.Visible = false;
        }

        public void FoldAction()
        {
            if (Table.List_player.Count >= 2  && Table.UserPlaying == Number)
            {
                next = true;

                SeatHand.Text = "";

                T_Portfolio portfolio = DataAccess.Portfolio.GetPortfolioByUserId(long.Parse(Session["facebook_userId"].ToString()));
                int amount = (int)portfolio.Amount;

                if (Bet.Text != "")
                {
                    amount = amount - int.Parse(Bet.Text);
                    Table.Pot += int.Parse(Bet.Text);
                    SeatNbChips.Text = amount.ToString();
                    portfolio.Amount = amount;
                    DataAccess.Portfolio.UpdatePortfolio(portfolio);

                    Bet.Text = "";
                }

                int reff = -1;

                for (int i = 0; i < Table.List_player.Count; i++)
                {
                    if (Table.List_player[i].Number == this.Number)
                    {
                        reff = i;
                        break;
                    }
                }

                if (reff != -1)
                    Table.List_player.RemoveAt(reff);

                PlayRound();

            }
        }

        public void CallAction()
        {
            if (Table.List_player.Count >= 2 && Table.UserPlaying == Number)
            {
                next = true;

                if (Table.Blind != 0)
                {
                    Bet.Text = Table.Blind.ToString();
                    Table.Pot += int.Parse(Bet.Text);

                    foreach (var item in Table.List_player)
                    {
                        if (item.Number == Number)
                        {
                            item.betPlayer = Table.Blind;
                            break;
                        }
                    }

                    T_Portfolio portfolio = DataAccess.Portfolio.GetPortfolioByUserId(long.Parse(Session["facebook_userId"].ToString()));
                    int amount = (int)portfolio.Amount;

                    amount = amount - int.Parse(Bet.Text);

                    if (amount < 0)
                        amount = 0;

                    SeatNbChips.Text = amount.ToString();
                    portfolio.Amount = amount;
                    DataAccess.Portfolio.UpdatePortfolio(portfolio);
                }

                PlayRound();
            }
        }

        public void RaiseAction(int raise)
        {

            if (Table.List_player.Count >= 2 && Table.UserPlaying == Number)
            {
                if (raise >= (2 * Table.Blind))
                {
                    next = true;

                    Bet.Text = raise.ToString();
                    Table.Pot += int.Parse(Bet.Text);

                    foreach (var item in Table.List_player)
                    {
                        if (item.Number == Number)
                        {
                            item.betPlayer = raise;
                            break;
                        }
                    }

                    T_Portfolio portfolio = DataAccess.Portfolio.GetPortfolioByUserId(long.Parse(Session["facebook_userId"].ToString()));
                    int amount = (int)portfolio.Amount;

                    amount = amount - int.Parse(Bet.Text);

                    if (amount < 0)
                        amount = 0;

                    SeatNbChips.Text = amount.ToString();
                    portfolio.Amount = amount;
                    DataAccess.Portfolio.UpdatePortfolio(portfolio);
                }

                PlayRound();
            }
        }

        public void PrintHand()
        {
            SeatHand.Text = hand.First.print() + ", " + hand.Second.print();
        }

        public void Change()
        {
            if (isDealer)
                Dealer.Text = "D";

            if (isBigBlind)
                Bet.Text = (Table.Category * 2).ToString();

            if (isSmallBlind)
                Bet.Text = (Table.Category).ToString();
        }

        public void PlayRound()
        {
            if (next)
                ((Table)this.Page).checkRound(this);
        }

        public int GetBet()
        {
            if (Bet.Text == "")
                return 0;

            return int.Parse(Bet.Text);
        }

        public void SetGain(int value)
        {
            SeatNbChips.Text = value.ToString();
            SeatHand.Text = "";
        }

        public void Fallcard()
        {
            SeatHand.Text = "";
        }

        public void SetSeat(String firstName, String avaterURL)
        {
            SeatFirstName.Text = firstName;
            SeatAvatar.ImageUrl = avaterURL;
            UpdateSeat.Update();
        }

        public void PrintWinner(T_User winner)
        {
            if (winner.IdUser == User.IdUser)
                SeatHand.Text = "Winner";
            else
                SeatHand.Text = "Looser";
        }
    }
}